$package('upms.organize');
upms.menu = function(){
	var _box = null;
	var _this = {
		addAction:baseUrl+'/organize/add',
		addUserAction:baseUrl+'/organize/addUser',
		editAction:baseUrl+'/organize/edit',
		deleteAction:baseUrl+'/organize/deleteOrganize',
		deleteUserAction:baseUrl+'/organize/deleteUser',
		queryOrgUserAction:baseUrl+'/organize/queryOrgUser',
		distributionAction:baseUrl+'/organize/distribution',
		editForm:function(){
			return $("#editForm");
		},
		editWin:function(){
			return $("#edit-win");
		},
		distributionForm:function(){
			return $("#distributionForm");
		},
		distributionWin:function(){
			return $("#distributionWin");
		},
		editWinUser:function(){
			return $("#edit-win-user");
		},
		editUserForm:function(){
			return $("#editUserForm");
		},
		add:function(){			
			if(_this.editForm().form('validate')){
				_this.editForm().attr('action',_this.addAction);
				upms.saveForm(_this.editForm(),function(data){
					var param = $("#searchForm").serializeObject();
					$("#data-list").datagrid('reload',param);
					_this.editWin().dialog('close');
					_this.loadMemuTrees();
				});
			}
		},
		addUser:function(){
			var organizeId;
			if($("#menuTrees").tree('getSelected')){
				$("#parentId").combotree("setValue",$("#menuTrees").tree('getSelected').id);
				organizeId = $("#menuTrees").tree('getSelected').id;
			} else {
				upms.alert('警告','请选中组织记录','warning');
				return;
			}
			
			var rows = $('#user-data-list').datagrid('getChecked');
			if (upms.checkSelect(rows)){
				var orgId = _this.editUserForm().find("input[name=organizeId]").val();
		    	var arr = [],idKey = 'userId'; //主键名称
		    	arr.push("organizeId="+orgId);
		    	$.each(rows,function(i,record){
		    		arr.push('userIds='+record[idKey]);
		    	});
		    	var data = arr.join("&");
		    	
		    	upms.deleteForm(_this.addUserAction,data,function(){
					var param = $("#searchForm").serializeObject();
					$("#data-list").datagrid('reload',param);
					_this.editWinUser().dialog('close');
				});
			}
			
		},
		edit:function(){
			if(_this.editForm().form('validate')){
				_this.editForm().attr('action',_this.editAction);
				upms.saveForm(_this.editForm(),function(data){
					var param = $("#searchForm").serializeObject();
					$("#data-list").datagrid('reload',param);
					_this.editWin().dialog('close');
					_this.loadMemuTrees();
				});
			}
		},
	    deleteData:function(){
			var orgId;
			if($("#menuTrees").tree('getSelected')){
				$("#parentId").combotree("setValue",$("#menuTrees").tree('getSelected').id);
				orgId = $("#menuTrees").tree('getSelected').id;
			} else {
				upms.alert('警告','请选中组织记录','warning');
				return;
			}
			var data ={};
			var idKey = 'organizeId'; //主键名称
				data[idKey] = orgId;
	 
			$.messager.confirm('Confirm','是否删除选中记录?',function(r){  
		    if (r){
			    	upms.deleteForm(_this.deleteAction,data,function(){
						var param = $("#searchForm").serializeObject();
						$("#data-list").datagrid('reload',param);
						_this.loadMemuTrees();
					});
		    	}  
			});
			
		},
	    deleteUserData:function(){
			var rows = $('#data-list').datagrid('getChecked');
			if (upms.checkSelect(rows)){
					$.messager.confirm('Confirm','是否删除选中记录?',function(r){  
				    if (r){
				    	var arr = [],idKey = 'userOrganizeId'; //主键名称
				    	$.each(rows,function(i,record){
				    		//将对象转成json字符串
				    		//var json = JSON.stringify(record);
				    		var userOrganizeId = record[idKey];
				    		arr.push('userOrganizeIds='+userOrganizeId);
				    	});
				    	var data = arr.join("&");
				    	upms.deleteForm(_this.deleteUserAction,data,function(){
							var param = $("#searchForm").serializeObject();
							$("#data-list").datagrid('reload',param);
						});
				    }  
				});
			}
		},
		loadParentMenuTree:function(){
			//编辑之前加载上级资源列表
			$("#parentId").combotree({
				url:baseUrl+'/organize/menuTree?applicationId='+applicationId
			});
		},
		loadMemuTrees:function(){
			$('#menuTrees').tree({
		          url:baseUrl+'/organize/menuTree?applicationId='+applicationId,
		          checkbox:false,
		          onClick:function(node){
		        	  if(node.id!=-1){
		        		  $("#searchForm").find("input[name=organizeId]").val(node.id);  
		        		  $("#searchForm").find("input[name=organizeName]").val('');  
		        	  }
		        	  var param = $("#searchForm").serializeObject();
					  $("#data-list").datagrid('reload',param);
					  $("#data-list").datagrid('unselectAll');
					  $("#data-list").datagrid('uncheckAll');
					  $("#user-data-list").datagrid('reload',param);
		          }
		    });
		},
		//设置默认按钮数据
		addDefBtns:function(){
			var defaultBtns= [
				{"menuName":"新增","linkUrl":"add"},
				{"menuName":"编辑","linkUrl":"edit"},
				{"menuName":"删除","linkUrl":"delete"}
			];
			var tbline = $(".tb-line:visible");
			$.each(defaultBtns,function(i,btn){
				var isExists = false;
				if(!isExists){
					_this.addLine(btn);
				}
			});
		},
		addLine: function(data){
			var table = $("#btn-tb");
			var	html = "<tr class='tb-line'>";
			html+=	   "	<td align='center'><span  class='newFlag red'>*</span></td>";
			html+=	   "	<td><input name=\"o_menuName\" class=\"easyui-validatebox text-name\" style=\"width:100%\" data-options=\"required:true\"></td>";
			html+=	   "	<td><input name=\"o_linkUrl\" class=\"easyui-validatebox text-desc\" style=\"width:100%\"  data-options=\"required:true\"></td>";
			html+=	   "	<td align='center'><a class=\"easyui-linkbutton remove-btn\"  iconCls=\"icon-remove\" plain=\"true\"></a>";
			html+=	   "	<input class=\"hidden\" name=\"o_menuId\">";
			html+=	   "	<input class=\"hidden\" name=\"o_deleted\" value=\"0\">";
			html+=	   "	</td>";
			html+=	   "</tr>";
			var line = $(html);
			//版定删除按钮事件
			$(".remove-btn",line).click(function(){
				upms.confirm('Confirm','确定要删除当前记录吗?',function(r){
					if(r){
						_this.delLine(line);
					}
				})
			});
			if(data){
				if(data.id){
					$(".newFlag",line).html(''); //清空新增标记
				}
				$("input[name='o_menuName']",line).val(data.menuName);
				$("input[name='o_linkUrl']",line).val(data.linkUrl);
				if(data.menuId){
					$("input[name='o_menuId']",line).val(data.menuId);
				}
				if(data.deleted){
					$("input[name='o_deleted']",line).val(data.deleted);
				}
			}
			$.parser.parse(line);//解析esayui标签
			table.append(line);
		},
		//删除全部
		delAllLine:function(b){
			if(b){
				$(".tb-line").remove();
			}else{
				$(".tb-line").each(function(i,line){
					_this.delLine($(line));
				});
			}
		},
		//删除单行
		delLine:function(line){
			if(line){
				var btnId = $("input[name='o_menuId']",line).val();
				if(btnId){
					$("input[name='o_deleted']",line).val(1); //设置删除状态
					line.fadeOut();
				}else{
					line.fadeOut("fast",function(){
						 $(this).remove();
					});
				}
			}
		},
		distribution:function(){
			var orgId;
			
			if($("#menuTrees").tree('getSelected')){
				$("#parentId").combotree("setValue",$("#menuTrees").tree('getSelected').id);
				orgId = $("#menuTrees").tree('getSelected').id;
			} else {
				upms.alert('警告','请选中组织记录','warning');
				return;
			}
			if(_this.distributionForm().form('validate')){
				
				//var nodes =$('#distributionTree').tree('getChecked',['checked','indeterminate']);//保存选中的节点id以及父节点
				var nodes =$('#distributionTree').tree('getChecked');
				var cnode='';
				for ( var i = 0; i < nodes.length; i++) {
					if (cnode != '') cnode += ',';
				   cnode += nodes[i].id;
				   }
				$("#distributionForm input[name='roleId']").val(cnode);
				$("#distributionForm input[name='organizeId']").val(orgId);
				
				_this.distributionForm().attr('action',_this.distributionAction);
				upms.saveForm(_this.distributionForm(),function(data){
					var param = $("#searchForm").serializeObject();
					$("#data-list").datagrid('reload',param);
					_this.distributionWin().dialog('close');
				});
			}
		},
		initForm:function(){
			_this.loadMemuTrees();
			//新增操作
			$("#addBtn").click(function(){
				$("#editForm").resetForm();
				_this.delAllLine(true);
				_this.loadParentMenuTree();
				if($("#menuTrees").tree('getSelected')){
					$("#parentId").combotree("setValue",$("#menuTrees").tree('getSelected').id);
				}
				$("#edit-win").dialog({
					buttons:[
						{
							text:'保  存',
							iconCls: 'icon-ok',
							handler:function(){
								_this.add(); 
							}
						},
						{
							text:'关  闭',
							iconCls: 'icon-cancel',
							handler:function(){
								_this.editWin().dialog('close');
							}
						}
				]});
				_this.editWin().dialog('open');
			});
			//删除操作
			$("#deleteBtn").click(function(){
				_this.deleteData();
			});
			
			//删除操作
			$("#deleteUserBtn").click(function(){
				_this.deleteUserData();
			});
			
			//修改操作
			$("#editBtn").click(function(){

				$("#editForm").resetForm();
				//只能对一条数据编辑
				var rows = $('#data-list').datagrid('getChecked');
				if(rows.length > 1){
					upms.alert('警告','请单选记录后，再进行操作.','warning');
					return false;
				}
				_this.delAllLine(true);
				_this.loadParentMenuTree();
				
				var orgId;
				
				if($("#menuTrees").tree('getSelected')){
					$("#parentId").combotree("setValue",$("#menuTrees").tree('getSelected').id);
					orgId = $("#menuTrees").tree('getSelected').id;
				} else {
					upms.alert('警告','请选中组织记录','warning');
					return;
				}
				var data ={};
				var idKey = 'orgId'; //主键名称
					data[idKey] = orgId;
			  upms.getById(baseUrl+"/organize/getById",data,function(result){	
				$("#editForm").form('load',result);
				$("#edit-win").dialog({
					buttons:[
						{
							text:'保  存',
							iconCls: 'icon-ok',
							handler:function(){
								_this.edit();
							}
						},
						{
							text:'关  闭',
							iconCls: 'icon-cancel',
							handler:function(){
								_this.editWin().dialog('close');
							}
						}
				]});
				_this.editWin().dialog('open');
			  });
			});
			$('#addLine_btn').click(_this.addLine);
			$('#addDefLine_btn').click(_this.addDefBtns);
			$('#delAllLine_btn').click(function(){
				upms.confirm('Confirm','确定删除所有记录吗?',function(r){
					_this.delAllLine(false);
				});
			});
			
			$('#distributionTree').tree({
		          url:baseUrl+'/menu/menuAndOperateTree?applicationId='+1,
		          checkbox:true
		          
		        /*  onCheck:function (node, checked){
		        	  var data = $('#distributionTree').tree('getData', node.target);  
		              var json = JSON.stringify(data);//字符串化节点信息以便使用post方法  
		              $("#distributionForm input[name='menuId']").val(json);
		              alert(json);
		              var nodes =$('#distributionTree').tree('getChecked');//保存选中的节点id
						
						for ( var i = 0; i < nodes.length; i++) {
						   cnode = nodes[i].id;
						   }
						alert(cnode);
		          }*/
		          
		    });
			//新增用户操作
			$("#addUserBtn").click(function(){
				$("#editUserForm").resetForm();
				_this.delAllLine(true);
				_this.loadParentMenuTree();
				var orgId;
				if($("#menuTrees").tree('getSelected')){
					$("#parentId").combotree("setValue",$("#menuTrees").tree('getSelected').id);
					orgId = $("#menuTrees").tree('getSelected').id;
				} else {
					upms.alert('警告','请选中组织记录.','warning');
					return;
				}
				
				var data ={};
				var idKey = 'organizeId'; //主键名称
					data[idKey] = orgId;
					upms.getById(_this.queryOrgUserAction,data,function(result){
					//
					_this.editUserForm().form('load',result);
					_this.editUserForm().find("input[name=organizeId]").val(orgId);
					$('#user-data-list').datagrid('unselectAll');
					$('#user-data-list').datagrid('uncheckAll');
					//选择一行
					var rows = $('#user-data-list').datagrid('getRows');
					$.each(rows,function(index,row){
						for(var i=0;i<result.length;i++){
							if(row.userId==result[i].userId){
								$('#user-data-list').datagrid('checkRow',index);
							}
						}
					})
					//
					
					$("#edit-win-user").dialog({
						buttons:[
							{
								text:'保  存',
								iconCls: 'icon-ok',
								handler:function(){
									_this.addUser(); 
								}
							},
							{
								text:'关  闭',
								iconCls: 'icon-cancel',
								handler:function(){
									_this.editWinUser().dialog('close');
								}
							}
					]});
					_this.editWinUser().dialog('open');
				});
			});
			
			//分配角色操作
			$("#distributionBtn").click(function(){
				$("#distributionForm").resetForm();
				//
				var orgId;
				if($("#menuTrees").tree('getSelected')){
					$("#parentId").combotree("setValue",$("#menuTrees").tree('getSelected').id);
					orgId = $("#menuTrees").tree('getSelected').id;
				} else {
					upms.alert('警告','请选中组织记录.','warning');
					return;
				}
				var data ={};
				var idKey = 'organizeId'; //主键名称
					data[idKey] = orgId;
					
					$('#distributionTree').tree({
				          url:baseUrl+'/organize/roleTree?applicationId='+applicationId,
				          checkbox:true,
				          onlyLeafCheck:true,
				          onLoadSuccess:function(){
				        	  	//初始化树
								$.ajax({
									url:baseUrl+'/organize/getRoleIdByOrgId?organizeId='+orgId,
									type:"get",
									dataType:"json",
									success:function(data){//直接就是一个数组   遍历树赋值 
										var nodes = $('#distributionTree').tree('getChildren');
										for ( var j = 0; j < data.length;j++) {
											for ( var i = 0; i < nodes.length; i++) {
											   if(nodes[i].id == data[j]){
												   $('#distributionTree').tree('check', nodes[i].target);
												   break;
											   }
											}
										}
									}
								});
				          }
				    });

 					$("#distributionWin").dialog({
   						buttons:[
   							{
   								text:'保  存',
   								iconCls: 'icon-ok',
   								handler:function(){
   									_this.distribution();
   								}
   							},
   							{
   								text:'关  闭',
   								iconCls: 'icon-cancel',
   								handler:function(){
   									_this.distributionWin().dialog('close');
   								}
   							}
   					]});
					_this.distributionWin().dialog('open');

			});
		},
		config:{
  			dataGrid:{
  				title:'用户列表',
	   			url:'dataList?applicationId='+applicationId,
	   			loadMsg:"处理中，请稍候…",
			    toolbar:"#toolbar",
			    idField:"userOrganizeId",
	   			columns:[[
						{field:'userOrganizeId',checkbox:true},
						{field:'userName',title:'用户名',width:120,align:'left',sortable:true},
						{field:'nickName',title:'昵称',width:160,align:'left',sortable:true},
						{field:'organizeName',title:'所属组织',width:160,align:'left',sortable:true},
						{field:'createTime',title:'创建时间',width:140,align:'center',sortable:true,formatter:upms.dateTimeFormatter}
				]]
			}
		},
		userConfig:{
  			dataGrid:{
	   			url:'userList',
	   			loadMsg:"处理中，请稍候…",
			    idField:"userId",
			    fitColumns:true,
	   			columns:[[
						{field:'userId',checkbox:true},
						{field:'userName',title:'用户名',width:120,align:'center',sortable:true},
						{field:'nickName',title:'昵称',width:80,align:'center',sortable:true},
						{field:'applicationName',title:'所属系统',width:100,align:'left',sortable:true,formatter:function(value,row,index){
							var applicationNames =row.applicationName.split(',');
							var selects="";
							for (var i = 0; i < applicationNames.length; i++) {
								selects+=''+applicationNames[i]+'<br/>';
							}
							
							return selects
						}}
						
				]]
			}
		},
		init:function(){
			_this.initForm();
			_box = new MyDataGrid(_this.config); 
			_box.init();
			$('#user-data-list').datagrid(_this.userConfig.dataGrid);
		}
	}
	_this._box = _box;
	return _this;
}();

$(function(){
	upms.menu.init();
});		